﻿package  
{
	import flash.display.Bitmap;
	import flash.display.DisplayObject;
	import flash.display.Loader;
	import flash.display.MovieClip;
	import flash.display.SpreadMethod;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	
	import com.mattlohkamp.src.as3.DisplayObjectGallery;
	
	/**
	 * ...
	 * @author matt lohkamp
	 */
	public class Demo extends MovieClip
	{		
		private var displayObjectGallery:DisplayObjectGallery;
		private var photoContainer:Sprite;
		
		private var firstButton:Sprite;
		private var previousButton:Sprite;
		private var nextButton:Sprite;
		private var lastButton:Sprite;
		
		private var images:Array;
		
		public function Demo(){
			loadXML('demo-external-content-ui.xml', function(e:Event){
				buildGallery(XML(e.target.data));
			});
		}
		private function loadXML(xmlURL:String, onLoad:Function){
			var xmlLoader:URLLoader = new URLLoader(new URLRequest(xmlURL));
			xmlLoader.addEventListener(Event.COMPLETE, onLoad);
		}
		private function buildGallery(galleryXML:XML){
			images = new Array();
			photoContainer = new Sprite();
			photoContainer.x = (this.stage.stageWidth / 2) - (Number(galleryXML.@width) / 2);
			photoContainer.y = (this.stage.stageHeight / 2) - (Number(galleryXML.@height) / 2);
			this.addChild(photoContainer);
			displayObjectGallery = new DisplayObjectGallery(null,Boolean(galleryXML.@allowLooping));
			for(var i in galleryXML.photo){
				var photoXML:XML = galleryXML.photo[i];
				var photoLoader:Loader = new Loader();
				photoLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, imageLoadCheck);
				photoLoader.load(new URLRequest(photoXML.toString()));
				images.push({
					index:i,
					content:new Bitmap,
					status:'loading',
					loader:photoLoader,
					textSnapshot:photoXML.@title
				});
			}
		}
		private function imageLoadCheck(e:Event){
			for(var i in images){
				var photoObject:Object = images[i];
				if(photoObject.loader == e.target.loader){
					photoObject.content = e.target.content;
					displayObjectGallery.add(photoContainer.addChild(photoObject.content));
					photoObject.status = 'ready';
				}
			}
		}
	}

}